import 'dart:convert';
import 'dart:io';

import 'package:afmjb1/mjb/utils.dart';
import 'package:appsflyer_sdk/appsflyer_sdk.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:webview_flutter/webview_flutter.dart';

// #docregion platform_imports
// Import for Android features.
//
// void main() {
//   runApp(const MyApp());
// }

// class MyApp extends StatelessWidget {
//   const MyApp({Key? key}) : super(key: key);
//
//   @override
//   Widget build(BuildContext context) {
//     return const MaterialApp(
//       home: Scaffold(
//         // appBar: AppBar(
//         //     title: const Text(
//         //   "com.sample.advent",
//         //   textDirection: TextDirection.ltr,
//         // )),
//         body: BWeb(),
//       ),
//     );
//   }
// }

class PrivacyWeb extends StatefulWidget {
  const PrivacyWeb({Key? key}) : super(key: key);

  @override
  _PrivacyWebState createState() => _PrivacyWebState();
}

class _PrivacyWebState extends State<PrivacyWeb> {
  WebViewController? _controller;
  late AppsflyerSdk appsflyerSdk;

  void printLog(Object? msg) {
    // if (kDebugMode) {
    print("printLog = $msg");
    //  }
  }

  void afStart() async {
    //com.hdknf.jdnbdjnfnbc	MuHPbGB2m7tXBVbBBT9YNS
    final AppsFlyerOptions options = AppsFlyerOptions(
        afDevKey: Utils.mAppsflyerKey,
        showDebug: true,
        timeToWaitForATTUserAuthorization: 15,
        manualStart: true);
    appsflyerSdk = AppsflyerSdk(options);

    // Init of AppsFlyer SDK
    await appsflyerSdk.initSdk(
        registerConversionDataCallback: true,
        registerOnAppOpenAttributionCallback: true,
        registerOnDeepLinkingCallback: true);
    // Conversion data callback
    appsflyerSdk.onInstallConversionData((res) {
      printLog("onInstallConversionData res: $res");
    });
    appsflyerSdk.startSDK(
      onSuccess: () {
        printLog("AppsFlyer SDK initialized successfully.");
      },
      onError: (int errorCode, String errorMessage) {
        printLog(
            "Error initializing AppsFlyer SDK: Code $errorCode - $errorMessage");
      },
    );
  }

  @override
  void initState() {
    super.initState();
    afStart();
  }

  final MethodChannel channel = const MethodChannel('com.google.BlueDiary');

  @override
  Widget build(BuildContext context) {
    String url = "";
    if (Platform.isAndroid) {
      url = Utils.mHttpUrl;
    }

    return WillPopScope(
      onWillPop: () async {
        return false;
      },
      child: Scaffold(
        body: SafeArea(
          child: Container(
            color: Colors.white,
            child: Padding(
                padding: const EdgeInsets.only(top: 0),
                child: WebView(
                  initialUrl: url,
                  navigationDelegate: (NavigationRequest request) {
                    printLog("request.url=${request.url}");
                    if (request.url.contains(".apk")) {
                      // 处理重定向逻辑
                      channel.invokeMethod("openBrowser", request.url);
                      return NavigationDecision.prevent;
                    }
                    return NavigationDecision.navigate;
                  },
                  javascriptMode: JavascriptMode.unrestricted,
                  javascriptChannels: {
                    // JavascriptChannel(
                    //     name: "toast",
                    //     onMessageReceived: (message) {
                    //       Fluttertoast.showToast(msg: message.message.toString());
                    //     }),

                    JavascriptChannel(
                        name: "jsBridge",
                        onMessageReceived: (message) {
                          try {
                            Fluttertoast.showToast(
                                msg: message.message.toString());
                            printLog("jsonDecode map=${message.message}");

                            Map<String, dynamic> map =
                                jsonDecode(message.message.toString());
                            printLog(
                                "jsonDecode method_name=${map["method_name"]}");
                            printLog("jsonDecode event=${map["event"]}");
                            printLog("jsonDecode data=${map["data"]}");

                            if (map["method_name"] == "postMessage") {
                              String event = map["event"]!;
                              if (event == "openURL") {
                                //系统浏览器
                                channel.invokeMethod("openBrowser", map["data"]);
                                return;
                              }

                              if (event == "openWindow") {
                                //系统浏览器
                                Map<String, dynamic> map2 =
                                    jsonDecode(map["data"]!);
                                channel.invokeMethod("openBrowser", map2["url"]);
                                return;
                              }

                              //金额
                              Map<String, dynamic> map3 =
                                  jsonDecode(map["data"]!);
                              if (map3.containsKey("amount")) {
                                map["af_currency"] = map3["amount"]!;
                              }
                              if (map3.containsKey("revenue")) {
                                map["af_revenue"] = map3["revenue"]!;
                              }
                              logEvent(event, map).then((value) => {});
                            } else if (map["method_name"] == "openAndroid") {
                              channel.invokeMethod("openBrowser", map["data"]);
                            }
                          } catch (e) {
                            printLog("catch=$e");
                          }
                        }),
                  },
                  onWebViewCreated: (controller) {
                    _controller = controller;
                  },
                )),
          ),
        ),
      ),
    );
  }

  Future<bool?> logEvent(String eventName, Map eventValues) {
    printLog("logEvent, eventName=$eventName,eventValues=$eventValues");
    return appsflyerSdk.logEvent(eventName, eventValues);
  }
}
